<#assign StringUtils = beansWrapperFn.getStaticModels()["org.apache.commons.lang3.StringUtils"]>
SELECT
T.`ROLE_CODE` AS 'ROLE_CODE', t.`PERMISSION_CODE` AS 'PERMISSION_CODE'
FROM
c1_role_permission AS t
WHERE (EXISTS
(SELECT
1
FROM
c1_us_group_role AS E
JOIN c1_us_group_user AS e_us_group_user
ON (e_us_group_user.`USER_GROUP_ID` = e.`USER_GROUP_ID`)
WHERE E.`ROLE_ID` = T.`ROLE_ID`
AND e_us_group_user.user_id = :userId
)
OR EXISTS
(SELECT
1
FROM
c1_role_user AS e
WHERE e.`ROLE_ID` = T.`ROLE_ID`
AND e.user_id = :userId
))
<#if StringUtils.isNotBlank(siteId)>
AND EXISTS (SELECT 1 FROM C1_PERMISSION AS E WHERE E.ID = T.PERMISSION_ID AND E.SITE_ID = :siteId)
</#if>
AND (T.`ROLE_CODE` IS NOT NULL OR T.`ROLE_CODE` <> '')
AND (T.`PERMISSION_CODE` IS NOT NULL OR T.`PERMISSION_CODE` <> '')
ORDER BY T.`ROLE_CODE` , LENGTH(t.`PERMISSION_CODE`) DESC
